package com.ztjava.member.controller;

import java.util.Date;

import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Ret;
import com.ztjava.core.Constant;
import com.ztjava.core.annotation.FrontMethod;
import com.ztjava.core.base.BaseController;
import com.ztjava.core.util.DateUtil;
import com.ztjava.core.util.RequestUtil;
import com.ztjava.member.model.MemberUser;
import com.ztjava.member.service.MemberService;
import com.ztjava.member.validator.RegisterValidator;
import com.ztjava.portal.validator.LoginValidator;

public class MemberController extends BaseController {
	@FrontMethod
	public void index(){
		renderFrontView("/member/index.html");
	}
	
	public void login(){
		renderFrontView("/member/login.html");
	}
	@Before(LoginValidator.class)
	public void loginCheck(){
		MemberUser memberUser = MemberUser.dao.findFirst("select id,password,enable_flag from "+MemberUser.tablename+" where username=?",
				getPara("username"));
		if(memberUser==null){
			renderError("用户不存在！");
			return;
		}
		if(!memberUser.getStr("password").equals(HashKit.md5(getPara("password")).toUpperCase())){
			renderError("用户名或密码错误！");
			return;
		}
		if(memberUser.getStr("enable_flag").equals("F")){
			renderError("账户已被停用！");
			return;
		}
		memberUser.set("last_login_time", DateUtil.getNowTime());
		memberUser.set("last_login_ip",RequestUtil.getIp(getRequest()));
		memberUser.update();
		setSessionAttr(Constant.FrontUser, memberUser.getInt("id"));
		renderSuccess("登录成功！");
	}
	public void logout(){
		removeSessionAttr(Constant.FrontUser);
		redirect("/member/login");
	}
	
	public void register(){
		renderFrontView("/member/register.html");
	}
	
	@Before(RegisterValidator.class)
	public void registerCheck(){
		MemberService memberService = Duang.duang(MemberService.class);
		MemberUser memberUser = new MemberUser();
		memberUser.set("group_id", getParaToInt("group_id"));
		memberUser.set("username", getPara("username"));
		memberUser.set("nickname", "SR_"+HashKit.sha1(DateUtil.formatDateToStr("HHmmss", new Date())).substring(0, 13)+DateUtil.formatDateToStr("dd", new Date()));
		memberUser.set("password", HashKit.md5(getPara("password")).toUpperCase());
		memberUser.set("email", getPara("email"));
		memberUser.set("source", "SelfRegister");
		memberUser.set("register_ip", RequestUtil.getIp(getRequest()));
		Ret ret = memberService.isRepeat(memberUser, MemberUser.tablename,
				new String[]{"username","String","用户名不能重复！"},
				new String[]{"email","String","邮箱不能重复！"});
		if(ret.get("result").equals("error")){
			renderError(ret.get("message").toString());
			return;
		}
		memberUser.save();
		memberService.updateMemberGroupAmount(getParaToInt("group_id"));
		renderSuccess("注册成功！");
	}
}
